package hhm.android.myframe

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.SystemClock
import android.view.Gravity
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.preferencesKey
import androidx.datastore.preferences.createDataStore
import hhm.android.base.activity.BaseActivity
import hhm.android.library.SwitchView
import hhm.android.library.chart.charts.LineChart
import hhm.android.library.chart.components.Legend
import hhm.android.library.chart.components.XAxis
import hhm.android.library.chart.data.Entry
import hhm.android.library.chart.data.LineData
import hhm.android.library.chart.data.LineDataSet
import hhm.android.library.chart.formatter.DateValueFormatter
import hhm.android.library.chart.formatter.IFillFormatter
import hhm.android.library.chart.highlight.Highlight
import hhm.android.library.chart.interfaces.datasets.ILineDataSet
import hhm.android.library.chart.listener.OnChartValueSelectedListener
import hhm.android.library.datePicker.bean.DateParams
import hhm.android.library.getPictureOrTakePhoto.TakePhotoPopWindow
import hhm.android.library.tablayout.SegmentTabLayout
import hhm.android.library.utils.DialogUtils
import hhm.android.library.utils.GetDateListener
import hhm.android.library.utils.GetStringListener
import hhm.android.library.utils.OnMultiClickListener
import hhm.android.myframe.room.DataBaseActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : BaseActivity(), OnChartValueSelectedListener {

    private val DATA_STORE_KEY = "DATA_STORE_KEY"
    private val NUMBER_KEY = preferencesKey<Int>("NUMBER_KEY")
    private var num: Int = 0
    lateinit var ds: DataStore<Preferences>
    lateinit var tv: TextView
    lateinit var stl: SegmentTabLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_main)
        ds = createDataStore(DATA_STORE_KEY)
        tv = findViewById(R.id.hhh_tv)
        stl = findViewById(R.id.tl_5)
        stl.setTabData(arrayOf("首页", "消息", "联系人"))
        stl.canUse = false

        val sw = findViewById<SwitchView>(R.id.sw)
        sw.setCanUse(false)

        chronometer.base = SystemClock.elapsedRealtime()
        chronometer.start()

//        XUpdate.newBuild(this)
//            .updateUrl("xuexiangjys/XUpdate/raw/master/jsonapi/update_test.json")
//            .update()

        ruler.setValue(10)
        value.text = "10"
        ruler.setOnValueChangeListener { s -> value.text = s.toString() }

//        DialogUtils.showHeightPicBottomView(this, "FT", object : GetStringListener {
//            override fun getString(s: String) {
//                Toast.makeText(this@MainActivity, s, Toast.LENGTH_LONG).show()
//            }
//        })


//        UpdateAppUtils.init(this)

        tete.setOnClickListener {
            DialogUtils.showWeightPicBottomView(this, "KG", 21.03, object : GetStringListener {
                override fun getString(s: String) {
                    Toast.makeText(this@MainActivity, s, Toast.LENGTH_LONG).show()
                }
            })
        }
        tete2.setOnClickListener {
            DialogUtils.showHeightPicBottomView(this, "FT", object : GetStringListener {
                override fun getString(s: String) {
                    Toast.makeText(this@MainActivity, s, Toast.LENGTH_LONG).show()
                }
            })
        }
        tete3.setOnClickListener {
            DialogUtils.showHeightPicBottomView(this, "CM", 63.toDouble(), object : GetStringListener {
                override fun getString(s: String) {
                    Toast.makeText(this@MainActivity, s, Toast.LENGTH_LONG).show()
                }
            })
//            DialogUtils.showHeightPicBottomView(this, "CM", object : GetStringListener {
//                override fun getString(s: String) {
//                    Toast.makeText(this@MainActivity, s, Toast.LENGTH_LONG).show()
//                }
//            })
        }

        two_page.setOnClickListener {
            startActivity(Intent(this, SecondActivity::class.java))
        }
        three_page.setOnClickListener {
            DialogUtils.showDatePicBottomView(
                this, object : GetDateListener {
                    override fun getDate(date: Date, string: String) {

                    }
                }, "HH:mm", DateParams.TYPE_HOUR, DateParams.TYPE_MINUTE
            )
//            showPopFormBottom()
//            showLoadingFragment(R.id.activity_main_fl)
//            startActivity(Intent(this, ThirdActivity::class.java))
        }
        database_page.setOnClickListener {
            startActivity(Intent(this, DataBaseActivity::class.java))
        }

        initChart()

//        Handler().postDelayed(Runnable {
//            val i = Intent(this, NetWorkDialog::class.java)
//            i.putExtra("type", 0)
//            startActivity(i)
//        }, 5000)
    }

    fun showPopFormBottom() {
        val takePhotoPopWin = TakePhotoPopWindow(this, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
            }
        }, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
            }
        })
        takePhotoPopWin.showAtLocation(findViewById(R.id.tete), Gravity.CENTER, 0, 0)
    }

    override fun onStart() {
        super.onStart()
        runBlocking {
            readNum()
        }
    }

    fun add(v: View) {
        num++
        tv.text = num.toString()

    }

    override fun onStop() {
        super.onStop()

        runBlocking {
            saveNum(num)
        }
    }

    private suspend fun readNum() {
        val nums = ds.data.map {
            it[NUMBER_KEY] ?: 0
        }
        this.num = nums.first()
    }

    private suspend fun saveNum(num: Int) {
        ds.edit {
            it[NUMBER_KEY] = num
        }
    }

    private fun initChart() {
        val chart: LineChart = findViewById(R.id.chart1)
        chart.setBackgroundColor(Color.WHITE)
        chart.description.isEnabled = true
        chart.setTouchEnabled(true)
        chart.setOnChartValueSelectedListener(this)
        chart.setDrawGridBackground(false)

        //点击的时候展示
//        val mv = MyMarkerView(this, R.layout.custom_marker_view)
//        mv.setChartView(chart)
//        chart.setMarker(mv)

        chart.isDragEnabled = true//拖拽
        chart.setScaleEnabled(true)//缩放
        //X轴可以缩放 Y轴禁止缩放
        chart.isScaleXEnabled = true
        chart.isScaleYEnabled = false
        //禁止双击
        chart.isDoubleTapToZoomEnabled = false

        // force pinch zoom along both axis
        chart.setPinchZoom(true)
        chart.setMaxVisibleValueCount(3)

        val values: ArrayList<Entry> = ArrayList<Entry>()
        val horizontal = arrayListOf(
            "2020-11-12",
            "2020-12-09",
            "2020-12-10",
            "2020-12-11",
            "2021-01-09",
            "2021-01-10"
        )

        val sdf = SimpleDateFormat("yyyy-MM-dd")

        values.add(Entry(sdf.parse(horizontal[0]).time.toFloat(), 19f))
        values.add(Entry(sdf.parse(horizontal[1]).time.toFloat(), 20f))
        values.add(Entry(sdf.parse(horizontal[2]).time.toFloat(), 21f))
        values.add(Entry(sdf.parse(horizontal[3]).time.toFloat(), 25f))
        values.add(Entry(sdf.parse(horizontal[4]).time.toFloat(), 23f))
        values.add(Entry(sdf.parse(horizontal[5]).time.toFloat(), 19f))

        val set1: LineDataSet
        set1 = LineDataSet(values, "")

        set1.mode = LineDataSet.Mode.CUBIC_BEZIER

        //icons指上面的星星
        set1.setDrawCircles(true)
        set1.setDrawIcons(true)
//        set1.setDrawIcons(true);

        set1.lineWidth = 3f
        set1.circleRadius = 3f


        set1.formLineWidth = 0f
        set1.formSize = 15f

        set1.valueTextSize = 9f

        //背景渐变色
        val drawable = ContextCompat.getDrawable(this, R.drawable.fade_blue)
        set1.fillDrawable = drawable

        set1.setDrawFilled(true)
        set1.fillFormatter =
            IFillFormatter { _, _ -> chart.axisLeft.axisMinimum }

        val dataSets: ArrayList<ILineDataSet> = ArrayList<ILineDataSet>()
        dataSets.add(set1)

        val data = LineData(dataSets)

        val xAxis: XAxis = chart.xAxis
        xAxis.setDrawGridLines(false)
        xAxis.labelCount = 3
        xAxis.setAvoidFirstLastClipping(true)
        xAxis.position = XAxis.XAxisPosition.BOTTOM
        xAxis.setDrawLimitLinesBehindData(true)
        xAxis.valueFormatter = DateValueFormatter()

        chart.axisLeft.setDrawLabels(false)
        chart.axisLeft.setDrawAxisLine(false)
        chart.axisLeft.setDrawGridLines(false)
        chart.axisRight.setDrawLabels(false)
        chart.axisRight.setDrawAxisLine(false)
        chart.axisRight.setDrawGridLines(false)

        chart.setBorderColor(Color.parseColor("#ffffff"))
        chart.description = null

        //隐藏左下角小方块  //图例
        val l: Legend = chart.legend
        l.isEnabled = false

        chart.data = data

    }

    override fun onValueSelected(e: Entry?, h: Highlight?) {}

    override fun onNothingSelected() {}

    override fun onPointerCaptureChanged(hasCapture: Boolean) {}
}